package com.jwt.token.filter;

import com.jwt.token.util.SessionUtil;
import com.jwt.token.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SessionFilter  implements Filter {
	public static final String TICKET = "ticket";
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("第1个filter初始化");
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		System.out.println("进入第1个filter");

		HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
		HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
		HttpSession session = httpRequest.getSession();
		SessionUtil.localSession.set(session);
		SessionUtil.localResponse.set(httpResponse);
		SessionUtil.localRequest.set(httpRequest);
		String ticketStr = httpRequest.getParameter(SessionFilter.TICKET);
		//带票据访问确定票据是否合法
		if(StringUtils.isNotEmpty(ticketStr)){
			boolean result = TokenUtil.verify(ticketStr);
			if(!result){
				System.out.println("票据验证失败");
				return;
			}else{
				String userName=TokenUtil.getUserName(ticketStr);
				SessionUtil.str.set("111111");
				SessionUtil.localSession.get().setAttribute("userName", userName);
				Map<String,String> map=new HashMap<>();
				map.put("test","test");
				SessionUtil.map.set(map);
			}
		}
		filterChain.doFilter(servletRequest,servletResponse);
		return;
	}

	@Override
	public void destroy() {
		System.out.println("第1个filter销毁");

	}
}
